{% extends "share/article.html" %}
{% block article %}
<div class="form-row">
    {% for key in conf[group_id] %}
    <div class="form-group col-md-4 ">
        <div class="input-group">
            <span class="form-control">{{ key }}</span>
            <button id="{{key}}" onclick="switcher('{{key}}')" class="switchButton">
                {{ conf[group_id][key] }}
            </button>
        </div>
    </div>
    {% endfor %}
</div>
<div class="form-row">
    <button onclick="onAll()" class="switchButton">全开</button>
    <!-- &emsp; -->
    <button onclick="offAll()" class="switchButton">全关</button>
    <!-- &emsp; -->
    <button onclick="save()" class="switchButton">保存</button>
</div>

{% endblock %}
{% block afterload %}
<script>
    const conf = JSON.parse('{{conf|tojson}}');
    let gid_str = '{{group_id}}';
    for (const key in conf[gid_str]) {
        console.log(key);
        if (conf[gid_str][key]) {
            document.getElementById(key).innerText = '开';
            document.getElementById(key).className = 'switchButton on';
        } else {
            document.getElementById(key).innerText = '关';
            document.getElementById(key).className = 'switchButton off';
        }
    }

    function save() {
        const url = '/manage/set';
        const request = new XMLHttpRequest();
        request.onload = function () {
            if (request.status === 200) {
                alert('设置成功');
            } else {
                alert('exception');
            }
        };

        request.open('POST', url);
        request.send(JSON.stringify(conf));
    }

    function set_conf(sv_name, is_enable) {
        conf[gid_str][sv_name] = is_enable;
        if (is_enable) {
            document.getElementById(sv_name).innerText = '开';
            document.getElementById(sv_name).className = 'switchButton on';
        } else {
            document.getElementById(sv_name).innerText = '关';
            document.getElementById(sv_name).className = 'switchButton off';
        }
    }

    function switcher(sv_name) {
        const old_status = conf[gid_str][sv_name];
        const new_status = (old_status + 1) % 2;
        set_conf(sv_name, Boolean(new_status));
    }

    function onAll() {
        for (const sv_name in conf[gid_str]) {
            if (conf[gid_str][sv_name] === false) {
                conf[gid_str][sv_name] = true;
                document.getElementById(sv_name).innerText = '开';
                document.getElementById(sv_name).className = 'switchButton on';
            }
        }
    }

    function offAll() {
        for (const sv_name in conf[gid_str]) {
            if (conf[gid_str][sv_name] === true) {
                conf[gid_str][sv_name] = false;
                document.getElementById(sv_name).innerText = '关';
                document.getElementById(sv_name).className = 'switchButton off';
            }
        }
    }
</script>
{% endblock %}